package org.pku_uestc.hackathon.bean;

import java.util.HashMap;
import java.util.Map;

import org.pku_uestc.hackathon.sensor.AirQualitySensor;
import org.pku_uestc.hackathon.sensor.SmartLight;
import org.pku_uestc.hackathon.sensor.TempHumSensor;

import android.annotation.SuppressLint;
import android.util.Log;

public class SensorFactory {

	private Map<Integer, Sensor> array;
	
	@SuppressLint("UseSparseArrays")
	public SensorFactory(int size){
		array = new HashMap<Integer, Sensor>();
	}
	
	public Sensor getSensor(int hashCode){
		if(array.get(hashCode)!=null)
			return array.get(hashCode);
		
		Sensor temp = null;
		switch(hashCode%100){
		case Sensor.TYPE_AIRQUALITY:
			temp = new AirQualitySensor(hashCode/100);
			break;
		case Sensor.TYPE_SMARTLIGHT:
			temp = SmartLight.getInstantces(hashCode/100);
			break;
		case Sensor.TYPE_TEMPHUMI:
			temp = new TempHumSensor(hashCode/100);
			break;
		}
		
		if(temp != null)
			array.put(hashCode, temp);
		return temp;
	}
	
	public Sensor getSensor(int type, int id){
		return this.getSensor(buildHash(type, id));
	}
	
	public void request(int minute){
		Log.d(getClass().getName(), "request");
		for(Integer i:array.keySet())
			array.get(i).request(minute);
	}
	
	public void addHandler(int type, int id, ISensorHandler handler){
		if(array.get(buildHash(type, id))!=null)
			array.get(buildHash(type, id)).addHandler(handler);
	}
	
	public void removeHandler(int type, int id, ISensorHandler handler){
		if(array.get(buildHash(type, id))!=null)
			array.get(buildHash(type, id)).removeHandler(handler);
	}
	
	private int buildHash(int type, int id){
		return type+id*100;
	}
}
